<?php
/**
 * Created by PhpStorm.
 * User: tangsian
 * Date: 2020/12/17
 * Time: 19:26
 */

namespace App\Http\Model\Api;


use App\Http\Model\Base;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class Room extends Base
{
    protected $table = 'room';
    protected $connection = "mysql_kkaudio";
    protected $primaryKey = 'room_id';
    protected $family_room = 'family_room';
    protected $family_table = 'family';
    protected $cacheRoomInfo = 'CACHE:SOUND_BYTE:ROOM_INFO:ROOM';
    protected $cacheFamilyRoomInfo = 'CACHE:SOUND_BYTE:ROOM_INFO_FAMILY:ROOM';

    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }

    public function getRoomInfo($room_id)
    {
        if (Redis::Exists($this->cacheRoomInfo . '_' . $room_id)) {
            return json_decode(Redis::get($this->cacheRoomInfo . '_' . $room_id), true);
        }
        $document = $this->objToArray(DB::connection($this->connection)->table($this->table)
            ->where('room_id', '=', $room_id)
            ->first());
        Redis::setex($this->cacheRoomInfo . '_' . $room_id, 2592000*2, json_encode($document));
        return $document;
    }

    /*
     * 获取房间工会信息
     */
    public function getRoomFamilyInfo($roomId)
    {
        if (Redis::Exists($this->cacheFamilyRoomInfo . '_' . $roomId)) {
            return json_decode(Redis::get($this->cacheFamilyRoomInfo . '_' . $roomId), true);
        }
        $condition = [$this->table . '.room_id' => $roomId];
        $fields = [$this->family_table . '.family_uid', $this->table . '.room_type', $this->table . '.business_type',$this->table.'.name',$this->table.'.image'];
        $document = self::objToArray(DB::connection($this->connection)->table($this->table)
            ->leftJoin($this->family_room, $this->family_room . '.room_id', '=', $this->table . '.room_id')
            ->leftJoin($this->family_table, $this->family_table . '.family_id', '=', $this->family_room . '.family_id')
            ->where($condition)
            ->first($fields));
        Redis::setex($this->cacheFamilyRoomInfo . '_' . $roomId, 2592000*2, json_encode($document));
        return $document;
    }

    /**
     *
     * @param $FamilyUIds
     * @return mixed
     */
    public function getFamilyInfoByIds($FamilyUIds)
    {
        $document = DB::connection($this->connection)->table($this->family_table)->whereIn('family_uid', $FamilyUIds)
            ->get()
            ->toArray();
        return self::objToArray($document);
    }
}
